package com.zoe.onelink.core.encryptor;

import com.zoe.onelink.annotation.data.encryptor.IEncryptor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>标题: 加密算法实例管理器,用于懒加载</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-11-12
 */
public class EncryptorManager {

    private final Map<String, IEncryptor> innerEncryptorMap = new ConcurrentHashMap<>();
    private static EncryptorManager self;

    public EncryptorManager(Map<String, IEncryptor> encryptorMap) {
        this.innerEncryptorMap.putAll(encryptorMap);
        self = this;
    }

    /**
     * 注册算法实例
     *
     * @param name      算法名称
     * @param encryptor 算法实例
     */
    public static boolean register(String name, IEncryptor encryptor) {
        String beanName = IEncryptor.BEAN_PREFIX.concat(name);
        if (self.innerEncryptorMap.containsKey(beanName)) {
            return false;
        }
        self.innerEncryptorMap.put(beanName, encryptor);
        return true;
    }

    /**
     * 获取算法实例
     *
     * @param name 算法名称
     */
    public static IEncryptor get(String name) {
        return self.innerEncryptorMap.get(IEncryptor.BEAN_PREFIX.concat(name));
    }

}
